﻿using C1.Win.C1Command;
using C1.Win.C1Ribbon;
using CWCS.BLL;
using CWCS.Common.Log;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace CWCS.UI
{
    public partial class FrmMain : C1RibbonForm
    {
        public const int WM_SYSCOMMAND = 0x112;
        public const int WM_MINIMIZE = 0xF020;
        public const int WM_MAXIMIZE = 0xF030;
        public const int WM_CLOSE = 0xF060;
        public const int WM_RESTORE = 0xF120;
        RobotBLL bll;
        Thread P_thread;
        Thread ProcessBar_thread;
        private LogHelper staManualLog = new LogHelper("staManualLog");

#pragma warning disable CS0169 // 从不使用字段“FrmMain.P_Scan_thread”
        Thread P_Scan_thread;
#pragma warning restore CS0169 // 从不使用字段“FrmMain.P_Scan_thread”
#pragma warning disable CS0618 // “ConfigurationSettings.AppSettings”已过时:“This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings”
        private string form = System.Configuration.ConfigurationSettings.AppSettings["FormStatus"].ToString();
#pragma warning restore CS0618 // “ConfigurationSettings.AppSettings”已过时:“This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings”
#pragma warning disable CS0618 // “ConfigurationSettings.AppSettings”已过时:“This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings”
        private string areacode = System.Configuration.ConfigurationSettings.AppSettings["AreaCode"].ToString();
#pragma warning restore CS0618 // “ConfigurationSettings.AppSettings”已过时:“This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings”
#pragma warning disable CS0618 // “ConfigurationSettings.AppSettings”已过时:“This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings”
        private string ZoneCode = System.Configuration.ConfigurationSettings.AppSettings["ZoneCode"].ToString();
        private string LineCode = System.Configuration.ConfigurationSettings.AppSettings["LineCode"].ToString();
        private string FaceCode = System.Configuration.ConfigurationSettings.AppSettings["FaceCode"].ToString();
#pragma warning restore CS0618 // “ConfigurationSettings.AppSettings”已过时:“This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings”
#pragma warning disable CS0618 // “ConfigurationSettings.AppSettings”已过时:“This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings”
        private string Version = System.Configuration.ConfigurationSettings.AppSettings["Version"].ToString();
#pragma warning restore CS0618 // “ConfigurationSettings.AppSettings”已过时:“This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings”
        public FrmMain()
        {
            InitializeComponent();
            MaximizedBounds = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
            timer1.Enabled = false;
            bll = new RobotBLL();
        }

        private void ShowTime(DateTime dt)
        {
            try
            {
                P_thread = new Thread(
                    () =>
                    {
                        while (true)
                        {
                            this.Invoke(
                                (MethodInvoker)delegate ()
                                //在对控件的 Invoke 方法进行调用时或需要一个简单委托又不想自己定义时可以使用该委托。   
                                {
                                    this.toolStripStatusLabel2.Text = "系统时间：" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                                    TimeSpan ts1 = new TimeSpan(dt.Ticks);
                                    TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
                                    TimeSpan ts3 = ts1.Subtract(ts2).Duration();
                                    this.toolStripStatusLabel3.Text = "运行时长：" + ts3.ToString("c");
                                    if (int.Parse(DateTime.Now.Subtract(BLLBase.loginTime).Duration().Minutes.ToString()) >= BLLBase.ActivieTime)
                                    {
                                        BLLBase.loginFlag = true;
                                        this.toolStripStatusLabel4.Text = "当前用户：无用户";//Application.ProductVersion.ToString();
                                    }
                                    else
                                        this.toolStripStatusLabel4.Text = "当前用户：" + BLLBase.user;//Application.ProductVersion.ToString();

                                });
                            Thread.Sleep(1000);
                        }
                    });
                P_thread.IsBackground = true;
                P_thread.Start();
            }
            catch (Exception e)
            {
                
            }
        }

        private void ShowProcessBar()
        {
            ProcessBar_thread = new Thread(
              () =>
              {
                  while (true)
                  {
                      this.Invoke(
                          (MethodInvoker)delegate()
                          //在对控件的 Invoke 方法进行调用时或需要一个简单委托又不想自己定义时可以使用该委托。   
                          {
                              if (this.toolStripStatusLabel1.Value < this.toolStripStatusLabel1.Maximum)
                              {
                                  int max = this.toolStripStatusLabel1.Value + 25;
                                  if (max > this.toolStripStatusLabel1.Maximum)
                                      this.toolStripStatusLabel1.Value = this.toolStripStatusLabel1.Maximum;
                                  else
                                      this.toolStripStatusLabel1.Value += 25;
                              }
                              else
                              {
                                  this.toolStripStatusLabel1.Value = 0;
                              }

                          });
                      Thread.Sleep(100);
                  }
              });
            ProcessBar_thread.IsBackground = true;
            ProcessBar_thread.Start();
        }

        /// <summary>
        /// 加载系统信息
        /// </summary>
        private void InitSysInfo()
        {
            DateTime dtStart = DateTime.Now;
            ShowTime(dtStart);
            ShowProcessBar();
            this.Text = areacode + "-" + LineCode + "-" + FaceCode + "面" + "-" + (ZoneCode.Equals("HC") ? "化成区" : "分容区") + "-" + "服务端";
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                MaximizedBounds = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
                InitSysInfo();
                LoadTabControl();

            }
            catch (Exception ex)
            {
                MessageBox.Show("系统信息:" + ex.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
        /// <summary>
        /// 加载TabControl
        /// </summary>
        private void LoadTabControl()
        {
            string[] l_form = form.Split(new char[] { ',' });
#pragma warning disable CS0219 // 变量“maintext”已被赋值，但从未使用过它的值
            string maintext = "";
#pragma warning restore CS0219 // 变量“maintext”已被赋值，但从未使用过它的值
#pragma warning disable CS0219 // 变量“index”已被赋值，但从未使用过它的值
            int index = -1;
#pragma warning restore CS0219 // 变量“index”已被赋值，但从未使用过它的值
            for (int i = 0; i < l_form.Length; i++)
            {
                if (l_form[i] == "1")
                {
                    switch (i)
                    {
                        case 0:
                            FrmConveryManager formsta = new FrmConveryManager();
                            ShowForm(formsta, "FrmConveryManager", "输送机管理");
                            break;
                        case 1:
                            FrmSRMManager formsc = new FrmSRMManager();
                            ShowForm(formsc, "FrmSRMManager", "堆垛机管理");
                            break;
                        case 2:
                            FrmRobotManager RoboManager = new FrmRobotManager();
                            ShowForm(RoboManager, "FrmRobotManager", "机械手管理");
                            break;
                        case 3:
                            FrmOCV OcvManager = new FrmOCV();
                            ShowForm(OcvManager, "FrmOCV", "专机设备管理");
                            break;
                        case 4:
                            FrmTaskManager TaskManager = new FrmTaskManager();
                            ShowForm(TaskManager, "FrmTaskManager", "WCS任务管理");
                            break;
                        case 5:
                            //if (ZoneCode == "FR")
                            //{
                                FrmDTSManager DTSManager = new FrmDTSManager();
                                ShowForm(DTSManager, "FrmDTSManager", "消防火警");                       
                           // }
                            break;
                    }
                }
            }
            //timer1.Enabled = true;
        }

        private C1DockingTabPage GetPage(string aKeyName)
        {
            C1DockingTabPage result;
            foreach (C1DockingTabPage c1DockingTabPage in this.tabMain.TabPages)
            {
                if (c1DockingTabPage.Name.Equals(aKeyName))
                {
                    result = c1DockingTabPage;
                    return result;
                }
            }
            result = null;
            return result;
        }

        public void ShowForm(Form aForm, string aKeyName, string aCaption)
        {

            C1DockingTabPage page = this.GetPage(aKeyName);
            if (page == null)
            {
                if (aForm != null)
                {
                    aForm.Text = aCaption;
                    aForm.TopLevel = false;
                    aForm.FormBorderStyle = FormBorderStyle.None;
                    aForm.Visible = true;
                    aForm.Dock = DockStyle.Fill;
                    C1DockingTabPage c1DockingTabPage = new C1DockingTabPage();
                    c1DockingTabPage.Controls.Add(aForm);
                    c1DockingTabPage.Text = aCaption;
                    c1DockingTabPage.Name = aKeyName;
                    this.tabMain.TabPages.Add(c1DockingTabPage);
                    aForm.Size = c1DockingTabPage.Size;
                    aForm.BackColor = this.tabMain.BackColor;
                }
            }
            else
            {
                this.tabMain.SelectedTab = page;
                this.tabMain.ScrollToSelectedTab();
                page.Show();
            }
        }

        private void ScanEquipmentStatus()
        {
            foreach (C1DockingTabPage tb in this.tabMain.TabPages)
            {
                if (!tb.Focused)
                {
                    foreach (Control c in tb.Controls)
                    {
                        if (c is FrmConveryManager)
                        {
                            FrmConveryManager frm = (FrmConveryManager)c;
                            if (frm.dicEquipStatus.ContainsValue(false))
                             {
                                    tb.TabBackColor = tb.TabBackColor == Color.Red ?Color.Transparent : Color.Red;
                                    tb.TabForeColor = Color.Red;
                                    break;
                             }
                        }
                        else if (c is FrmSRMManager)
                        {
                            FrmSRMManager frm = (FrmSRMManager)c;
                            if (frm.dicEquipStatus.ContainsValue(false))
                                tb.TabBackColor = tb.TabBackColor == Color.Red ? Color.Transparent : Color.Red;
                        }
                    }
                }
            }
        }

        #region 窗体事件
        protected override void WndProc(ref   Message m)
        {
            if (m.Msg == WM_SYSCOMMAND)
            {
                int wParam = (int)m.WParam;
                //拦截 除最小化 恢复 关闭 以外的消息
                if (wParam != WM_MINIMIZE && wParam != WM_CLOSE && wParam != WM_RESTORE && wParam != WM_MAXIMIZE)
                {
                    return;
                }
            }
            base.WndProc(ref   m);
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            this.ShowInTaskbar = false;
            this.ShowIcon = false;
            this.WindowState = FormWindowState.Minimized;
            e.Cancel = true;
        }

        private void CloseCtiServer()
        {
            if (ProcessBar_thread != null)
                ProcessBar_thread.Abort();
            if (P_thread != null)
                P_thread.Abort();
            this.notifyWCS.Dispose();
            Application.ExitThread();
            this.Close();
            Application.Exit();
            System.Environment.Exit(0);
        }

        private void HideCtiServer()
        {
            this.Hide();
        }

        private void ShowCtiServer()
        {
            this.Show();
            this.WindowState = FormWindowState.Maximized;
            this.Activate();
        }

        private void showToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowCtiServer();
        }

        private void hideToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HideCtiServer();
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (!BLLBase.loginFlag)
            //{
            //    FrmLogIn frmLogIn = new FrmLogIn();
            //    frmLogIn.ShowDialog();
            //}
            //if (!BLLBase.loginFlag)
            //{
            //    MessageBox.Show("用户校验失败,请重新校验!");
            //    return;
            //}
            BLLBase.loginTime = DateTime.Now;
            staManualLog.Info("用户:" + BLLBase.user + "退出WCS系统!");
            CloseCtiServer();
        }
        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            ScanEquipmentStatus();
        }
        private void toolStripStatusLabel5_Click(object sender, EventArgs e)
        {
            BLLBase.loginFlag = true;
            BLLBase.user = "无用户";
            MessageBox.Show("用户注销成功!");
        }
    }
}
